<template xmlns:dict-tag="http://www.w3.org/1999/html">
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="病患姓名" prop="patientName">
        <el-input
          v-model="queryParams.patientName"
          placeholder="请输入病患姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-input
          v-model="queryParams.gender"
          placeholder="请输入性别"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="年龄" prop="age">
        <el-input
          v-model="queryParams.age"
          placeholder="请输入年龄"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="联系电话" prop="phoneNumber">
        <el-input
          v-model="queryParams.phoneNumber"
          placeholder="请输入联系电话"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
<!--      <el-form-item label="地址" prop="address">-->
<!--        <el-input-->
<!--          v-model="queryParams.address"-->
<!--          placeholder="请输入地址"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="入院时间" prop="admissionTime">-->
<!--        <el-date-picker clearable-->
<!--          v-model="queryParams.admissionTime"-->
<!--          type="date"-->
<!--          value-format="yyyy-MM-dd"-->
<!--          placeholder="请选择入院时间">-->
<!--        </el-date-picker>-->
<!--      </el-form-item>-->
<!--      <el-form-item label="更新时间" prop="updatedAt">-->
<!--        <el-date-picker clearable-->
<!--          v-model="queryParams.updatedAt"-->
<!--          type="date"-->
<!--          value-format="yyyy-MM-dd"-->
<!--          placeholder="请选择更新时间">-->
<!--        </el-date-picker>-->
<!--      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['his:patient:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['his:patient:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['his:patient:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['his:patient:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="patientList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="患者ID" align="center" prop="id" />
      <el-table-column label="病患姓名" align="center" prop="patientName" />
      <el-table-column label="性别" align="center" prop="gender" />
      <el-table-column label="年龄" align="center" prop="age" />
      <el-table-column label="联系电话" align="center" prop="phoneNumber" />
      <el-table-column label="地址" align="center" prop="address" />
      <el-table-column label="入院时间" align="center" prop="admissionTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.admissionTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.patient_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="updatedAt" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updatedAt, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['his:patient:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['his:patient:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="openTreatmentRecordForm(scope.row)"
            v-hasPermi="['his:patient:treatment']"
          >诊断</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="openOrderForm(scope.row)"
            v-hasPermi="['his:patient:order']"
          >医嘱</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改病患信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="病患姓名" prop="patientName">
          <el-input v-model="form.patientName" placeholder="请输入病患姓名" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-input v-model="form.gender" placeholder="请输入性别" />
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model="form.age" placeholder="请输入年龄" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phoneNumber">
          <el-input v-model="form.phoneNumber" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入地址" />
        </el-form-item>
        <el-form-item label="入院时间" prop="admissionTime">
          <el-date-picker clearable
            v-model="form.admissionTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择入院时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in dict.type.patient_status"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="更新时间" prop="updatedAt">
          <el-date-picker clearable
            v-model="form.updatedAt"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择更新时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogVisible" title="新增诊疗记录">
      <el-form :model="treatmentRecordForm" ref="treatmentForm" label-width="120px">
        <el-form-item label="病患姓名">
          <el-input v-model="treatmentRecordForm.patientName" :disabled="true"></el-input>
        </el-form-item>

        <el-form-item label="选择医生">
          <el-select v-model="treatmentRecordForm.doctorId" placeholder="医生姓名"
                     clearable
                     filterable
                     @blur="selectDoctorBlur($event)"
                     default-first-option
                     allow-create>
            <el-option
              v-for="item in doctorList"
              :key="item.id"
              :label="item.doctorName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="诊断结果">
          <el-input v-model="treatmentRecordForm.diagnosis" type="textarea" placeholder="请输入诊断结果"></el-input>
        </el-form-item>

        <el-form-item label="治疗方案">
          <el-input v-model="treatmentRecordForm.prescription" type="textarea" placeholder="请输入治疗方案"></el-input>
        </el-form-item>

        <el-form-item label="备注">
          <el-input v-model="treatmentRecordForm.notes" type="textarea" placeholder="请输入备注"></el-input>
        </el-form-item>

        <el-form-item>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitTreatmentRecord">提交</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog :visible.sync="isDialogVisible" title="新增医嘱记录">
      <el-form :model="OrderForm" ref="treatmentForm" label-width="120px">
        <el-form-item label="病患姓名">
          <el-input v-model="OrderForm.patientName" :disabled="true"></el-input>
        </el-form-item>

        <el-form-item label="医嘱类型">
          <el-select v-model="OrderForm.orderStatus" placeholder="医嘱状态" clearable>
            <el-option
              v-for="dict in dict.type.order_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="医嘱详情">
          <el-input v-model="OrderForm.orderDetail" type="textarea" placeholder="请输入治疗方案"></el-input>
        </el-form-item>

        <el-form-item label="医嘱时间">
          <el-date-picker clearable
                          v-model="OrderForm.orderTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择医嘱时间">
          </el-date-picker>
        </el-form-item>

        <el-form-item>
          <el-button @click="isDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitOrder">提交</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>

</template>

<script>
import {listPatient, getPatient, delPatient, addPatient, updatePatient, listPatientAll} from "@/api/his/patient";
import dict from "@/utils/dict";
import {parseTime} from "../../../utils/ruoyi";
import request from '@/utils/request';  // 导入 axios 请求封装工具
import {addRecord} from '@/api/his/record'
import {listDoctorAll} from "@/api/his/doctor";
import {addOrder} from "@/api/his/order";
export default {
  name: "Patient",
  dicts:['patient_status','order_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 病患信息表格数据
      patientList: [],
      doctorList: [],  // 医生数据列表
      isDialogVisible: false,
      dialogVisible: false, // 弹窗控制
      selectedPatient: null, // 当前选择的病患
      treatmentRecordForm: {
        patientName: '', // 病患姓名
        doctorId: null,  // 医生ID
        diagnosis: '',   // 诊断
        prescription: '', // 处方
        notes: '',         // 备注
      },
      OrderForm:{
        patientName: '',
        orderStatus: null,
        orderTime: '',
        orderDetail: '',
        status: 0
      },
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        patientName: null,
        gender: null,
        age: null,
        phoneNumber: null,
        address: null,
        admissionTime: null,
        status: null,
        updatedAt: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        patientName: [
          { required: true, message: "病患姓名不能为空", trigger: "blur" }
        ],
        gender: [
          { required: true, message: "性别不能为空", trigger: "blur" }
        ],
        age: [
          { required: true, message: "年龄不能为空", trigger: "blur" }
        ],
        phoneNumber: [
          { required: true, message: "联系电话不能为空", trigger: "blur" }
        ],
        address: [
          { required: true, message: "地址不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "状态不能为空", trigger: "change" }
        ],
      }
    };
  },
  created() {
    this.loadPatientList() // 加载医生列表
    this.getList();
    this.getDicts("patient_status").then((res)=>{
      this.status = res.data;
    })
  },
  methods: {
    parseTime,
    dict,
    /** 查询病患信息列表 */

    loadPatientList() {
      listPatientAll().then(resp => {
        this.patientList = resp.rows;
      });
    },
    // 获取医生列表
    loadDoctors() {
      listDoctorAll().then(resp=> {
        this.doctorList = resp.rows;
      });
    },
    // 打开诊疗记录表单
    openTreatmentRecordForm(patient) {
      this.selectedPatient = patient;
      this.treatmentRecordForm.patientName = patient.patientName; // 填充病患姓名
      if (this.selectedPatient.status==0){
        this.dialogVisible = true;
      }else {
        this.$message.error('病人已出诊,请重新选择病患');
      }


      // 加载医生列表
      this.loadDoctors();
    },
    openOrderForm(patient){
      this.selectedPatient = patient;
      this.OrderForm.patientName = patient.patientName;
      if (this.selectedPatient.status==0){
        this.isDialogVisible=true;
      }else {
        this.$message.error('病人已出诊,请重新选择病患');
      }
    },
    // 保存诊疗记录
    submitTreatmentRecord() {
      const params = {
        patientId: this.selectedPatient.id,  // 当前病患ID
        treatmentTime: new Date(),           // 设置治疗时间为当前时间
        doctorId: this.treatmentRecordForm.doctorId,
        diagnosis: this.treatmentRecordForm.diagnosis,
        prescription: this.treatmentRecordForm.prescription,
        notes: this.treatmentRecordForm.notes,
        updatedAt: new Date()                // 更新记录时间
      };

      // 请求接口保存诊疗记录
      this.loading = true; // 开始加载

      addRecord(params).then(response => {
        this.loading = false; // 完成请求

        // 判断返回的 response.code 是否为 200
        if (response.code === 200) {
          // 如果操作成功，显示成功提示
          this.$message.success(response.msg || '诊疗记录添加成功');
          this.dialogVisible = false; // 关闭弹出表单

          // 清空表单数据
          this.resetForm();

          // 提交成功后重新加载病患列表
          // this.loadPatientList();
        } else {
          // 如果返回的 code 不是 200，显示错误信息
          this.$message.error(response.msg || '添加诊疗记录失败');
        }
      }).catch(error => {
        this.loading = false; // 完成请求
        console.error('请求出错:', error);
        this.$message.error('添加诊疗记录失败，请稍后重试');
      });
    },
    submitOrder(){
      const params={
        patientId: this.selectedPatient.id,
        orderTime: this.OrderForm.orderTime,
        orderDetail: this.OrderForm.orderDetail,
        orderStatus: this.OrderForm.orderStatus,
        status:this.OrderForm.status,
        updatedAt: new Date()                // 更新记录时间
      }
      this.loading=true
      addOrder(params).then(respone=>{
        this.loading=false
        if (respone.code===200){
          this.$message.success(respone.msg||'医嘱添加成功');
          this.isDialogVisible=false
          this.resetOrderForm()
        }else {
          this.$message.error(respone.msg||'添加医嘱失败');
        }
      }).catch(error =>{
        this.loading=false;
        console.error('请求出错:', error);
        this.$message.error('添加医嘱失败，请稍后重试');
      })
    },
    resetForm() {
      this.treatmentRecordForm = {
        patientName: '', // 病患姓名
        doctorId: null,  // 医生ID
        diagnosis: '',   // 诊断
        prescription: '', // 处方
        notes: ''         // 备注
      };
    },
    resetOrderForm(){
      this.OrderForm = {
        patientName: '',
        orderStatus: null,
        orderTime: '',
        orderDetail: '',
        status: 0
      }
    },
    getList() {
      this.loading = true;
      listPatient(this.queryParams).then(response => {
        this.patientList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    selectDoctorBlur(e) {
      if (e.target.value !== '') {
        this.$set(this.queryParams, 'doctorId', e.target.value);
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        patientName: null,
        gender: null,
        age: null,
        phoneNumber: null,
        address: null,
        admissionTime: null,
        status: null,
        updatedAt: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加病患信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getPatient(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改病患信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updatePatient(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPatient(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除病患信息编号为"' + ids + '"的数据项？').then(function() {
        return delPatient(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('his/patient/export', {
        ...this.queryParams
      }, `patient_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
